package com.yunpeng.dishes.start;

import com.yunpeng.common.dto.Result;
import com.yunpeng.dishes.common.enums.ResultCodeEnum;
import com.yunpeng.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ProjectControllerAdvice 项目的全局错误拦截器
 *
 * @author : Moore(hemw)
 * @date : 2020-03-13
 */
@RestControllerAdvice
public class ProjectControllerAdvice {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectControllerAdvice.class);

    @Value(value = "${debug}")
    private Boolean debug;

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result<String> errorHandler(Exception ex, HttpServletRequest request) {
        LOGGER.error("捕获到异常: ", ex);
        ResultCodeEnum resultCodeEnum = ResultCodeEnum.FAIL;
        //不同类型的异常可以有各自不同的返回code和label
        String msg = ex.getMessage();
        Integer code = resultCodeEnum.getValue();
        if (ex instanceof BizException) {
            code = ((BizException) ex).getCode();
            msg = ((BizException) ex).getMsg();
        }
        //返回结果
        return Result.build(code, msg, ex.getMessage());
    }

}